import logging
from django.shortcuts import render
from django.views import View
from django import http
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.utils import timezone  # 处理时间

from datetime import datetime
from goods.utils import get_breadcrumb
from goods.models import GoodsCategory, SKU, GoodsVisitCount
from contents.utils import get_categories
from meiduo_mall.utils.response_code import RETCODE
from . import constants
from . import models
# Create your views here.
logger = logging.getLogger('django')


class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self, request, category_id):
        """
        记录分类商品访问量
        - 如果访问记录存在，说明今天不是第一次访问，不新建记录，访问量直接累加。
        - 如果访问记录不存在，说明今天是第一次访问，新建记录并保存访问量。
        """
        # 校验参数，查看传入的id是否能够在商品表中找到
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden
        # 获取当天时间
        t = timezone.localtime()
        today_str = '%d-%02d-%02d' % (t.year, t.month, t.day)
        # 将当天的时间字符串转成时间对象datetime, 日期格式化
        today_date = datetime.strptime(today_str, '%Y-%m-%d')

        # 判断当天中指定的分类商品对应的记录是否存在
        try:
            # 如果存在,直接获取到记录对应的对象
            counts_data = category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            # 如果不存在,直接创建记录对应的对象
            counts_data = GoodsVisitCount()
        try:
            counts_data.category = category
            counts_data.count += 1
            counts_data.save()
        except Exception as e:
            logger.error(e)
            return http.HttpResponseServerError('统计失败')
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = models.SKU.objects.get(id=sku_id)
        except models.SKU.DoesNotExist:
            return render(request, '404.html')

        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)

        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """
            获取商品销量排行
        """
        # 首先,查询指定分类的SKU信息,而且必须是上架的状态
        # 然后,按照销量由高到低排序
        # 最后,切片取出前两位
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[:2]
        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,  # 图片的全路径
                'name': sku.name,
                'price': sku.price
            })
        return http.JsonResponse({'code':RETCODE.OK, 'errmsg':'OK', 'hot_skus':hot_skus})


class ListView(View):
    """商品列表页"""
    def get(self, request, category_id, page_num):
        # 校验参数category_id是否合法
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('参数category_id不存在')
        # 接收sort参数：如果用户不传，就是默认的排序规则
        sort = request.GET.get('sort', 'default')
        # 查询面包屑导航: 一级 -> 二级 -> 三级
        breadcrumb = get_breadcrumb(category)
        # 根据sort选择排序字段, 排序字段必须是模型类的属性
        if sort == 'price':
            sort_field = 'price' # 按照价格由低到高排序
        elif sort == 'hot':
            sort_field = '-sales' # 按照销量由高到低(倒序)排序
        else:
            # 'price'和'sales'以外的所有排序方式都归为'default'
            sort = 'default'
            sort_field = 'create_time'

        # skus 会返回总的记录
        skus = category.sku_set.filter(is_launched=True).order_by(sort_field)
        categories = get_categories()

        # 创建分页器：每页N条记录
        # Paginator('要分页的记录', '每页记录的条数')
        paginator = Paginator(skus, constants.GOODS_LIST_LIMIT)
        try:
            # 获取到用户当前要看的那一页(核心数据)
            page_skus = paginator.page(page_num)
        except PageNotAnInteger:
            # 如果page不是一个整数
            page_skus =paginator.page(1)
        except EmptyPage:
            # 如果page_num不正确，默认给用户返回当前页
            page_skus = paginator.page(paginator.num_pages)

        # 获取总页数: 前端的分页插件需要使用
        total_page = paginator.num_pages

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'page_skus': page_skus,
            'total_page': total_page,
            'page_num': page_num,
            'sort': sort,
            'category_id':category_id,
        }
        return render(request, 'list.html', context)

